package com.wxm.common.file.core.service.supplier;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import com.wxm.common.file.core.exception.FileException;
import com.wxm.common.file.core.property.TencentCloudCosProperty;
import com.wxm.common.file.core.property.UploadBaseProperty;

import java.io.InputStream;

/**
 * <p>
 *      供应商[腾讯云Cos文件储存]Service
 * </p>
 *
 * @author: wxm
 * @Date: 2022/1/28
 */
public class TencentCloudCosService implements SupplierBaseService{
    private TencentCloudCosProperty property;
    private COSClient cosClient;

    private void init(){
        //1.设置用户身份信息。
        COSCredentials cred = new BasicCOSCredentials(this.property.getSecretId() ,this.property.getSecretKey());
        // 2 设置 bucket 的地域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        Region region = new Region(this.property.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // https 协议
        clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        this.cosClient = new COSClient(cred, clientConfig);
    }
    /**
     * 参数非空校验
     */
    private void checkProperty(){
        FileException.isNull(this.property.getSecretId(),"SecretId不能为null");
        FileException.isNull(this.property.getSecretKey(),"SecretKey不能为null");
        FileException.isNull(this.property.getRegion(),"Region不能为null");
        FileException.isNull(this.property.getBucket(),"Bucket不能为null");
        FileException.isNull(this.property.getRootPath(),"RootPath不能为null");
    }

    @Override
    public void init(UploadBaseProperty uploadBaseProperty) {
        this.property = (TencentCloudCosProperty) uploadBaseProperty;
        this.checkProperty();
        this.init();
    }

    @Override
    public void uploading(InputStream inputStream, String fileName) throws Exception {
        PutObjectRequest putObjectRequest = new PutObjectRequest(this.property.getBucket(), fileName, inputStream,new ObjectMetadata());
        this.cosClient.putObject(putObjectRequest);
        this.cosClient.shutdown();
    }

    @Override
    public void delete(String filePath) throws Exception {
        filePath = this.removeFilePathPrefix(filePath,this.property.getRootPath());
        this.cosClient.deleteObject(this.property.getBucket(), filePath);
        this.cosClient.shutdown();
    }
}
